from selenium.webdriver.support.ui import WebDriverWait
import time
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.select import Select

class Base():
    # 初始化驱动
    def __init__(self,driver):
        self.driver = driver

    # 封装打开网址
    def open_url(self,url):
        self.driver.get(url)

    # 封装截屏方法
    def saveshot(self):
        t = time.strftime('%Y%m%d%H%M%S')
        self.driver.save_screenshot(t + '.png')

    # 封装定位方式
    def find_element(self,loc):
        # 异常处理
        try:
            WebDriverWait(self.driver,20,0.5).until(lambda driver: driver.find_element(*loc).is_displayed())
            return self.driver.find_element(*loc)
        except Exception as e:
            # 调用截图方法
            self.saveshot()
            print(e)

    # 封装点击操作
    def click(self,loc):
        self.find_element(loc).click()

    # 封装输入操作
    def send_keys(self,loc,text):
        self.find_element(loc).send_keys(text)

    # 滚动条的封装
    def scrollTo(self,x):
        self.driver.execute_script(f'window.scrollTo(0,{x})')

    # 弹框处理 两种
    # 确认
    def alert_accept(self):
        alert = self.driver.switch_to.alert
        alert.accept()
    # 取消
    def alert_dismiss(self):
        alert = self.driver.switch_to.alert
        alert.dismiss()

    # iframe处理
    def frame(self,loc):
       self.driver.switch_to.frame(self.find_element(loc))

    # 切换页面
    def new_window(self):
        self.driver.switch_to.window(self.driver.window_handles[-1])

    # 鼠标双击事件
    def double_click(self,loc):
        c = self.find_element(loc)
        ActionChains(self.driver).double_click(c).perform()

    # 键盘回车事件
    def key_enter(self,loc,text):
        self.find_element(loc).send_keys(text,Keys.ENTER)

    # 浏览器返回事件
    def back(self):
        self.driver.back()
    # 浏览器前进事件
    def forward(self):
        self.driver.forward()

    # 下拉框选择
    # value值
    def select_by_value(self,loc,value):
        s = Select(self.find_element(loc))
        s.select_by_value(value)
    # 下标
    def select_by_index(self,loc,index):
        s = Select(self.find_element(loc))
        s.select_by_index(index)
    # 文本
    def select_by_visible_text(self,loc,text):
        s = Select(self.find_element(loc))
        s.select_by_visible_text(text)

    # 清除文本封装
    def clear(self,loc):
        self.find_element(loc).clear()









